<template>
  <div class="permission-cache-manager">
    <!-- 缓存状态显示 -->
    <div class="cache-status" v-if="showStatus">
      <el-tag 
        :type="cacheStatus.type" 
        :icon="cacheStatus.icon"
        size="small"
      >
        {{ cacheStatus.text }}
      </el-tag>
      <span class="cache-info">
        权限数量: {{ permissionCount }} | 
        更新时间: {{ lastUpdateTime }}
      </span>
    </div>

    <!-- 缓存操作按钮 -->
    <div class="cache-actions" v-if="showActions">
      <el-button 
        type="primary" 
        size="small" 
        :loading="refreshing"
        @click="refreshCache"
      >
        <el-icon><Refresh /></el-icon>
        刷新权限
      </el-button>
      <el-button 
        type="warning" 
        size="small" 
        @click="clearCache"
      >
        <el-icon><Delete /></el-icon>
        清除缓存
      </el-button>
    </div>

    <!-- 缓存详情 -->
    <div class="cache-details" v-if="showDetails">
      <el-collapse>
        <el-collapse-item title="权限缓存详情" name="cache-details">
          <div class="cache-details-content">
            <div class="detail-item">
              <span class="label">菜单权限:</span>
              <span class="value">{{ menuPermissionCount }} 个</span>
            </div>
            <div class="detail-item">
              <span class="label">缓存时间:</span>
              <span class="value">{{ cacheDuration }}</span>
            </div>
            <div class="detail-item">
              <span class="label">是否过期:</span>
              <span class="value">
                <el-tag :type="isExpired ? 'danger' : 'success'" size="small">
                  {{ isExpired ? '已过期' : '有效' }}
                </el-tag>
              </span>
            </div>
          </div>
        </el-collapse-item>
      </el-collapse>
    </div>
  </div>
</template>

<script setup lang="ts">
/**
 * 权限缓存管理组件
 * @author Wu.Liang
 * @date 2024-12-21
 * @description 优化权限缓存机制，提供缓存状态监控和手动刷新功能
 */
import { computed, ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Refresh, Delete, Check, Warning, Clock } from '@element-plus/icons-vue'
import { usePermissionStore } from '@/store/permission'
import { useUserStore } from '@/store/user'
import { showSuccess, showError, showWarning, showInfo } from '@/utils/message'

interface Props {
  /** 是否显示缓存状态 */
  showStatus?: boolean
  /** 是否显示操作按钮 */
  showActions?: boolean
  /** 是否显示缓存详情 */
  showDetails?: boolean
  /** 自动刷新间隔（毫秒），0表示不自动刷新 */
  autoRefreshInterval?: number
}

const props = withDefaults(defineProps<Props>(), {
  showStatus: true,
  showActions: true,
  showDetails: false,
  autoRefreshInterval: 0
})

const permissionStore = usePermissionStore()
const userStore = useUserStore()
const refreshing = ref(false)
let autoRefreshTimer: NodeJS.Timeout | null = null

// 停车权限缓存管理
const parkingPermissionCache = ref<any>(null)
const parkingPermissionLoading = ref(false)

/**
 * 缓存状态
 */
const cacheStatus = computed(() => {
  if (!permissionStore.permissions.length) {
    return {
      type: 'warning',
      icon: Warning,
      text: '未加载'
    }
  }
  
  if (permissionStore.isPermissionExpired()) {
    return {
      type: 'danger',
      icon: Clock,
      text: '已过期'
    }
  }
  
  return {
    type: 'success',
    icon: Check,
    text: '正常'
  }
})

/**
 * 权限数量
 */
const permissionCount = computed(() => {
  return permissionStore.permissions.length
})

/**
 * 菜单权限数量
 */
const menuPermissionCount = computed(() => {
  return permissionStore.menuPermissions.length
})

/**
 * 最后更新时间
 */
const lastUpdateTime = computed(() => {
  if (!permissionStore.lastPermissionUpdate) {
    return '未更新'
  }
  
  const date = new Date(permissionStore.lastPermissionUpdate)
  return date.toLocaleString('zh-CN')
})

/**
 * 缓存持续时间
 */
const cacheDuration = computed(() => {
  if (!permissionStore.lastPermissionUpdate) {
    return '0分钟'
  }
  
  const duration = Date.now() - permissionStore.lastPermissionUpdate
  const minutes = Math.floor(duration / (1000 * 60))
  
  if (minutes < 60) {
    return `${minutes}分钟`
  }
  
  const hours = Math.floor(minutes / 60)
  const remainingMinutes = minutes % 60
  
  if (hours < 24) {
    return `${hours}小时${remainingMinutes}分钟`
  }
  
  const days = Math.floor(hours / 24)
  const remainingHours = hours % 24
  
  return `${days}天${remainingHours}小时${remainingMinutes}分钟`
})

/**
 * 是否过期
 */
const isExpired = computed(() => {
  return permissionStore.isPermissionExpired()
})

/**
 * 刷新权限缓存
 */
const refreshCache = async () => {
  if (refreshing.value) return
  
  // 只有已登录且token存在才刷新权限
  const token = localStorage.getItem('token')
  if (!token || !userStore.isLogged) {
    showError('未登录，无法刷新权限缓存')
    return
  }
  
  try {
    refreshing.value = true
    
    // 清除权限缓存
    permissionStore.refreshPermissionCache()
    
    // 重新获取权限
    await permissionStore.getMenuPermissions(userStore.userRoles)
    
    showSuccess('权限缓存刷新成功')
    
  } catch (error) {
    console.error('刷新权限缓存失败:', error)
    showError('权限缓存刷新失败')
  } finally {
    refreshing.value = false
  }
}

/**
 * 清除权限缓存
 */
const clearCache = () => {
  try {
    permissionStore.resetPermissions()
    showSuccess('权限缓存已清除')
  } catch (error) {
    console.error('清除权限缓存失败:', error)
    showError('清除权限缓存失败')
  }
}

/**
 * 启动自动刷新
 */
const startAutoRefresh = () => {
  if (props.autoRefreshInterval > 0) {
    autoRefreshTimer = setInterval(() => {
      if (permissionStore.isPermissionExpired()) {
        refreshCache()
      }
    }, props.autoRefreshInterval)
  }
}

/**
 * 停止自动刷新
 */
const stopAutoRefresh = () => {
  if (autoRefreshTimer) {
    clearInterval(autoRefreshTimer)
    autoRefreshTimer = null
  }
}

/**
 * 获取停车权限缓存状态
 */
const getParkingPermissionCacheStatus = async () => {
  try {
    parkingPermissionLoading.value = true
    const response = await parkingPermissionAPI.getCurrentUserCacheStatus()
    if (response.code === 200) {
      parkingPermissionCache.value = response.data
    }
  } catch (error) {
    console.error('获取停车权限缓存状态失败:', error)
  } finally {
    parkingPermissionLoading.value = false
  }
}

/**
 * 刷新停车权限缓存
 */
const refreshParkingPermissionCache = async () => {
  try {
    await parkingPermissionAPI.refreshCurrentUserCache()
    showSuccess('停车权限缓存刷新成功')
    await getParkingPermissionCacheStatus()
  } catch (error) {
    console.error('刷新停车权限缓存失败:', error)
    showError('刷新停车权限缓存失败')
  }
}

/**
 * 清除停车权限缓存
 */
const clearParkingPermissionCache = async () => {
  try {
    await parkingPermissionAPI.clearCurrentUserCache()
    showSuccess('停车权限缓存清除成功')
    await getParkingPermissionCacheStatus()
  } catch (error) {
    console.error('清除停车权限缓存失败:', error)
    showError('清除停车权限缓存失败')
  }
}

// 组件挂载时启动自动刷新
onMounted(() => {
  startAutoRefresh()
  getParkingPermissionCacheStatus()
})

// 组件卸载时停止自动刷新
onUnmounted(() => {
  stopAutoRefresh()
})

// 暴露方法供父组件调用
defineExpose({
  refreshParkingPermissionCache,
  clearParkingPermissionCache,
  getParkingPermissionCacheStatus
})
</script>

<style lang="scss" scoped>
.permission-cache-manager {
  .cache-status {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-bottom: 12px;
    
    .cache-info {
      font-size: 12px;
      color: #909399;
    }
  }
  
  .cache-actions {
    display: flex;
    gap: 8px;
    margin-bottom: 12px;
  }
  
  .cache-details {
    .cache-details-content {
      .detail-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 8px 0;
        border-bottom: 1px solid #f0f0f0;
        
        &:last-child {
          border-bottom: none;
        }
        
        .label {
          font-weight: 500;
          color: #303133;
        }
        
        .value {
          color: #606266;
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .permission-cache-manager {
    .cache-status {
      flex-direction: column;
      align-items: flex-start;
      gap: 8px;
    }
    
    .cache-actions {
      flex-direction: column;
      
      .el-button {
        width: 100%;
      }
    }
  }
}
</style> 